import { Stream } from 'adajs';

class RouteStream extends Stream {
    oncreated() {
        let context = this.context;
        let _hack = (type) => {
            let origin = context.window.history[type];
            return function (...args) {
                let e = new context.window.Event(type);
                e.arguments = args;
                context.window.dispatchEvent(e);
                return origin.apply(this, args);
            };
        };
        context.window.history.pushState = _hack('pushState');
        context.window.history.replaceState = _hack('replaceState');
        context.window.addEventListener('popstate', () => this.next(context.window.location.pathname));
        context.window.addEventListener('replaceState', () => this.next(context.window.location.pathname));
        context.window.addEventListener('pushState', () => this.next(context.window.location.pathname));
    }

    open({ path, title = '' }) {
        if (this.context.window.location.pathname !== path) {
            this.context.window.history.pushState({}, title, path);
        }
    }

    replace({ path, title = '' }) {
        if (this.context.window.location.pathname !== path) {
            this.context.window.history.replaceState({}, title, path);
        }
    }
}

export default RouteStream;